﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SimpleWebApp.Demo02
{
    public class Startup
    {
        // 注意，方法名称不能错
        public void ConfigureServices(IServiceCollection services)
        {
            Console.WriteLine("01 Startup -> ConfigureServices");

            var provider = services.BuildServiceProvider();
            foreach (var service in services)
            {
                var serviceTypeName = GetName(service.ServiceType);
                var implementionType = service.ImplementationType
                    ?? service.ImplementationInstance?.GetType()
                    ?? service.ImplementationFactory?.Invoke(provider)?.GetType();

                if (implementionType != null)
                {
                    Console.WriteLine($"{service.Lifetime,-15}{ GetName(service.ServiceType),-50}{ GetName(implementionType)}");
                }
            }
        }

        // 只能有一个参数
        // 并且这个参数是 IServiceCollection 类型        
        public void ConfigureContainer(IServiceCollection services)
        {
            Console.WriteLine("02 Startup -> ConfigureContainer");
        }

        // 注意，方法名称不能错
        public void Configure(IApplicationBuilder app)
        {
            Console.WriteLine("03 Startup -> Configure");

            app.UseMiddleware<StringContentMiddlewareV2>("Hello v5 World!", false);
        }


        private string GetName(Type type)
        {
            if (!type.IsGenericType)
            {
                return type.Name;
            }
            var name = type.Name.Split('`')[0];
            var args = type.GetGenericArguments().Select(it => it.Name);
            return $"{name}<{string.Join(",", args)}>";
        }
    }
}
